package com.chuhe.lottery.dao;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chuhe.lottery.domain.entity.PrizePools;
import com.chuhe.lottery.mapper.PrizePoolsMapper;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 张楚河
 * @since 2025-06-03
 */
@Service
public class PrizePoolsDao extends ServiceImpl<PrizePoolsMapper, PrizePools> {
    /**
     * 查询（指定）奖品库存
     * @Author: 楚河
     * @Date: 2025-06-03 17:28
     */
    public Integer selectPrizePoolsCount() {
        return lambdaQuery()
                .in(PrizePools::getId, Arrays.asList(1, 2, 3))
                .gt(PrizePools::getCounts, 0)
                .count();
    }

    /**
     * 扣减库存（乐观锁）
     * @Author: 楚河
     * @Date: 2025-06-03 18:12
     */
    public void delPrizePoolsCount(int winnerNum) {
        //1. 查询数据  获取当前 version
        PrizePools prizePools = lambdaQuery().eq(PrizePools::getId,winnerNum).one();
        if (prizePools == null || prizePools.getCounts() <= 0) {
            throw new RuntimeException("奖品不存在或库存不足");
        }

        //2. 修改库存
        prizePools.setCounts(prizePools.getCounts() - 1);
        //3. 更新
        boolean success = this.updateById(prizePools);
        if (!success) {
            throw new RuntimeException("库存更新失败，请重试");
        }
    }

    /**
     * 查询
     * @Author: 楚河
     * @Date: 2025-06-03 22:20
     */
    public PrizePools selectById(int winnerNum) {
        return lambdaQuery()
                .eq(PrizePools::getId, winnerNum)
                .one();
    }

    /**
     * 查询奖池信息
     * @Author: 楚河
     * @Date: 2025-06-04 8:42
     */
    public List<PrizePools> selectAll() {
        return lambdaQuery()
                .list();
    }
}
